package com.letv.so.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 修改记录：<br>
 * 1.2010-11-24 djg 加入GZIP解析功能.<br>
 * 
 * @author jiangongduan
 * 
 */
public final class HttpUtil {

	private static final Log log = LogFactory.getLog(HttpUtil.class);

	public static final String readContent(String url) {

		String content = "";
		int count = 0;
		while (true) {
			count++;
			try {
				content = readContend(url, 800, 800);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if ((StringUtils.isNotBlank(content) && !content.equals("-1")) || count == 5) {
				break;
			}
		}
		return content;
	}

	public static final String readContend(String url, int contimeout, int readtimeout) {
		URL url1 = null;
		BufferedReader reader = null;
		HttpURLConnection connection = null;
		try {
			url1 = new URL(url);
			connection = (HttpURLConnection) url1.openConnection();
			connection.setConnectTimeout(contimeout);// 设置连接主机超时（单位：毫秒）
			connection.setReadTimeout(readtimeout); // 设置从主机读取数据超时（单位：毫秒）
			connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
			//connection.
			connection.connect();

			String contentEncoding = connection.getContentEncoding();// 编码
			InputStream stream;
			if (null != contentEncoding && -1 != contentEncoding.indexOf("gzip")) {
				stream = new GZIPInputStream(connection.getInputStream());
			} else if (null != contentEncoding && -1 != contentEncoding.indexOf("deflate")) {
				stream = new InflaterInputStream(connection.getInputStream());
			} else {
				stream = connection.getInputStream();
			}
			reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = reader.readLine()) != null) {
				// logger.debug(line);
				sb.append(line).append("\n");
			}
			reader.close();
			connection.disconnect();
			return sb.toString();
		} catch (IOException e) {
			log.error("连接url: " + url + "错误",e);
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					log.error("读关闭错误");
				}
			}

			return "-1";
		} finally {
			url1 = null;
			if (connection != null)
				connection.disconnect();
		}
	}

	public static String getUrlDate(String urlStr, int contimeout, int readtimeout) {
		
		InputStream in = null;
		try {
			
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setReadTimeout(contimeout);
			conn.setConnectTimeout(readtimeout);//毫秒
			try{
				in = url.openStream();
			}catch (Exception e) {
				log.error("连接url: " + url + "错误");
			}
			
	        StringBuffer s = new StringBuffer();
	        String rLine = null;
	        BufferedReader bReader = new BufferedReader(new InputStreamReader(in,"utf-8"));
	        while ( (rLine = bReader.readLine()) != null) {
	            String tmp_rLine = rLine;
	            int str_len = tmp_rLine.length();
	            if (str_len > 0) {
	              s.append(tmp_rLine);
	            }
	            tmp_rLine = null;
	       }
			in.close();
			return s.toString();
		} catch (Exception e) {
			log.error("连接url错误");
			return "";
		}
	}
	/**
	 * @param arg
	 */
	public static void main(String arg[]) {
		//Random rnd = new Random();
		String usl = "http://video.baidu.com/v?ct=301989888&rn=20&pn=0&db=0&s=0&fbl=800&fix_tpl=1&otype=json&word=???&ie=utf-8";
		System.out.println(readContend(usl,400,400).trim());
	
	}
}
